﻿using Common;
using Entity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Renovation.Filters;
using Renovation.Models;

namespace Renovation.Controllers
{
    public class EmployeeController : Controller
    {
        MyDbContext db;
        public EmployeeController(MyDbContext myDb)
        {
            db = myDb;
        }
        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        public IActionResult LoginView()
        {
            return View();
        }
        /// <summary>
        /// 员工列表页面
        /// </summary>
        /// <returns></returns>
        [LoginFilter]
        public IActionResult EmployeeListView()
        {
            return View();
        }
        /// <summary>
        /// 员工添加页面
        /// </summary>
        /// <returns></returns>
        public IActionResult CreateEmployeeView()
        {
            return View();
        }
        /// <summary>
        /// 修改员工页面
        /// </summary>
        /// <returns></returns>
        public IActionResult UpdateEmployeeView() {
            return View();
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public APIResultModel Login(string account, string password)
        {
            //参数验证
            if (string.IsNullOrEmpty(account))
            {
                return APIResultModel.GetErrorResult("请输入账号");
            }
            if (string.IsNullOrEmpty(password))
            {
                return APIResultModel.GetErrorResult("请输入密码");
            }
            //通过账号查找一个员工的信息
            Employee employee = db.Employees.FirstOrDefault(e => e.Account == account);
            if (employee == null) {
                return APIResultModel.GetErrorResult("请输入正确的账号");
            }
            //验证密码
            string md5Pwd = MD5Helper.CreateMD5(password);
            if (employee.Password != md5Pwd) {
                return APIResultModel.GetErrorResult("请输入正确的密码");
            }
            //session保存用户信息
            HttpContext.Session.SetString("UserName",employee.Name);
            return APIResultModel.GetSuccessResult("登录成功");
        }
        /// <summary>
        /// 添加员工
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public APIResultModel CreateEmployee(string name,string account,string password,string phone,string roleId)
        {
            //参数验证
            if(string.IsNullOrEmpty(name))
            {
                return APIResultModel.GetErrorResult("请输入姓名"); 
            }
            if (string.IsNullOrEmpty(account))
            {
                return APIResultModel.GetErrorResult("请输入账号");
            }
            if (string.IsNullOrEmpty(password))
            {
                return APIResultModel.GetErrorResult("请输入密码");
            }
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();

            //创建员工
            Employee employee = new Employee();
            employee.Id = Guid.NewGuid().ToString();
            employee.Name = name;
            employee.Account = account;
            employee.CreateTime = DateTime.Now;
            employee.Phone = phone;
            employee.RoleId = roleId;
            //md5加密
            string md5Pwd = MD5Helper.CreateMD5(password);
            employee.Password = md5Pwd;
            //向数据集添加
            dbContext.Employees.Add(employee);
            //保存
            dbContext.SaveChanges();

            return APIResultModel.GetSuccessResult("注册成功");
        }
        /// <summary>
        /// 获取一个员工的数据
        /// </summary>
        /// <returns></returns>
        public APIResultModel GetEmployee(string id)
        {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();

            //查看第一条数据
            //Employee employee = dbContext.Employees.First();
            //Employee employee = dbContext.Employees.FirstOrDefault();
            //条件筛选
            //Employee employee = dbContext.Employees.FirstOrDefault(e => e.Id == "1");
            //return employee;
            Employee employee = dbContext.Employees.FirstOrDefault(e=>e.Id == id);
            return APIResultModel.GetSuccessResult("成功", employee);
        }
        /// <summary>
        /// 获取多条数据
        /// </summary>
        /// <returns></returns>
        public object GetEmployeeList(int page,int limit,string name,string account)
        {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();
            //查询所有的员工
            //List<Employee> list = dbContext.Employees.ToList();
            //条件查询
            //List<Employee> list = dbContext.Employees.Where(e => e.Id == "1").ToList();
            //OrderBy升序，OrderByDescending降序，Skip跳过多少条数据，Take获取多少条数据
            //List<Employee> list = dbContext.Employees.OrderByDescending(e=>e.CreateTime).Skip((page-1)*limit).Take(limit).ToList();

            //还没有查询出来的数据集
            //IQueryable<Employee> list = dbContext.Employees.Where(e=>e.IsDelete == false);

            //左连接
            var list = from e in dbContext.Employees.Where(e => e.IsDelete == false)
                       join r in dbContext.RoleInfo.Where(r => r.IsDelete == false)
                       on e.RoleId equals r.Id
                       into tempR
                       from rr in tempR.DefaultIfEmpty()
                       select new
                       {
                           e.Id,
                           e.Name,
                           e.Phone,
                           e.Account,
                           e.CreateTime,
                           RoleName = rr.Name
                       };
            //name有数据
            if (!string.IsNullOrEmpty(name))
            {
                
                list = list.Where(e => e.Name.Contains(name));
            }
            //account有数据
            if (!string.IsNullOrEmpty(account))
            {
                list = list.Where(e => e.Account.Contains(account));
            }
            //先排序再分页，OrderBy升序，OrderByDescending降序
            List<EmployeeModel> res = list.OrderByDescending(e => e.CreateTime).Skip((page - 1) * limit).Take(limit).Select(e => new EmployeeModel() {
                Id = e.Id,
                Name = e.Name,
                Account = e.Account,
                CreateTime = e.CreateTime.ToString("yyyy-MM-dd hh:mm:ss"),
                RoleName = e.RoleName,
                Phone = e.Phone
            }).ToList();
            //获取一共有多少条数据
            int count = list.Count();
            return APIResultModel.GetSuccessResultForLayui("成功", count, res);

        }

        /// <summary>
        /// 删除一个员工
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public APIResultModel DeleteEmployee(string id)
        {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();
            //Employee employee = new Employee();
            //employee.Id = id;
            ////从数据集中删除员工
            //dbContext.Employees.Remove(employee);
            //先查询员工
            Employee employee = dbContext.Employees.FirstOrDefault(e => e.Id == id);
           
            if (employee != null)
            {
                //员工存在删除
                //dbContext.Employees.Remove(employee);
                //int index = dbContext.SaveChanges();
                //return "ok";
                employee.IsDelete = true;
                employee.DeleteTime = DateTime.Now;
                //保存
                dbContext.SaveChanges();

                return APIResultModel.GetSuccessResult("成功");
            }
            else
            {
                //员工不存在报错
                //return "error";
                return APIResultModel.GetErrorResult("失败");
            }


        }
        /// <summary>
        /// 批量删除员工
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public APIResultModel BatchDeleteEmployee(List<string> ids) {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();

            foreach (var id in ids) {
                //先查询员工是否存在
                Employee employee = dbContext.Employees.FirstOrDefault(e => e.Id == id);

                if (employee != null) {
                    employee.IsDelete = true;
                    employee.DeleteTime = DateTime.Now;
                }
            }
            //保存
            int index = dbContext.SaveChanges();
            return APIResultModel.GetSuccessResult("成功");
        }
        /// <summary>
        /// 修改员工
        /// </summary>
        /// <param name="id"></param>
        ///  /// <param name="name"></param>
        /// <returns></returns>
        public APIResultModel UpdateEmployee(string id, string name,string phone,string roleId)
        {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();
            //先查询员工
            Employee employee = dbContext.Employees.FirstOrDefault(e => e.Id == id);

            if (employee != null)
            {
                //员工存在修改
                employee.Name = name;
                employee.Phone = phone;
                employee.RoleId = roleId;
                int index = dbContext.SaveChanges();
                return APIResultModel.GetSuccessResult("成功");
            }
            else
            {
                //员工不存在报错
                return APIResultModel.GetSuccessResult("失败");
            }

        }
        /// <summary>
        /// 获取员工的下拉集合
        /// </summary>
        /// <returns></returns>
        public APIResultModel GetSelectOptions()
        {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();
            var res = dbContext.Employees.Where(e => e.IsDelete == false).Select(r => new
            {
                Title = r.Name,
                Value = r.Id
            }).ToList();
            return APIResultModel.GetSuccessResult("成功", res);
        }
    }
}
